<template>
  <div class="material-application">
    <!-- 左边 -->
    <div class="left">
      <div class="box-title">
        <div class="box-title-circle"></div>
        <div class="box-title-label">我的项目（合同）</div>
      </div>
      <el-input
        class="left-input"
        v-model="contractFrom.keyword"
        placeholder="请输入客户/小区名称"
        :prefix-icon="Search"
        @change="contractChange"
        style="width: 100%"
      />
      <ul class="left-scrollbar" v-infinite-scroll="load" :infinite-scroll-immediate="false" v-loading="contractLoading">
        <template v-for="item in contractList" :key="item.contractId">
          <div class="left-item" :class="{ active: contractId == item.contractId }" @click="idxChange(item)">
            <div class="title-name">
              <el-tooltip effect="dark" :content="item.customerName" placement="top-start">
                <el-text class="name" truncated>{{ item.customerName }}</el-text>
              </el-tooltip>
              <el-divider direction="vertical" />
              <el-tooltip effect="dark" :content="item.residence" placement="top-start">
                <el-text class="title" truncated>{{ item.residence }}</el-text>
              </el-tooltip>
            </div>
            <div class="contract-type">{{ item.contractName }}</div>
          </div>
        </template>
        <div class="left-scrollbar-loading">{{ contractLoading ? "加载中..." : isMore ? "上拉加载更多" : "没有更多数据了" }}</div>
      </ul>
    </div>
    <!-- 右边 -->
    <div class="right">
      <el-scrollbar class="head-scrollbar">
        <div class="head-list" v-loading="stepListLoading">
          <template v-for="(item, index) in stepList" :key="item.stageTaskId">
            <div class="head-item">
              <div v-if="item.status == 1" class="item-type to-begin">待开始</div>
              <div v-if="item.status == 2" class="item-type in-progress">进行中</div>
              <div v-if="item.status == 3" class="item-type complete">已完成</div>
              <el-tooltip class="box-item" effect="dark" :content="item.taskName" placement="top-start">
                <div class="item-text">{{ item.taskName }}</div>
              </el-tooltip>
              <div class="item-time">{{ item.status == 3 ? "完成" : "计划" }}：{{ item.startDate }}</div>
              <img class="mask-icon" src="@/assets/images/image/mask-icon.png" alt="" />
              <template v-if="item.isAlreadyBuy !== null">
                <div class="item-state" v-if="item.isAlreadyBuy == 1" :style="bgColor(1)">自购丨已采</div>
                <div class="item-state" v-else-if="item.isAlreadyBuy == 0 && item.overdueStatus == 1" :style="bgColor(3)">
                  自购丨超期未采
                </div>
                <div class="item-state" v-else-if="item.isAlreadyBuy == 0" :style="bgColor(2)">自购丨未采</div>
              </template>
            </div>
            <img v-if="index < stepList.length - 1" class="arrow" src="@/assets/images/image/arrow.png" alt="" />
          </template>
        </div>
      </el-scrollbar>
      <div class="right-table">
        <div class="table-top">
          <div class="table-top-tabs">
            <el-radio-group class="radio" v-model="radioTabs" fill="#fff" text-color="#007DFF" @change="radioTabsChange">
              <el-radio-button :label="`已申领（${applyTotal}）`" :value="1" />
              <el-radio-button :label="`审核信息（${applyLoadingTotal}）`" :value="2" />
            </el-radio-group>
          </div>
          <div class="table-top-text">
            <template v-if="isJudgmentShowApplyGoodsCost">
              合计辅材成本：¥{{ auxiliaryMaterialAmount.finishAmount }}/总辅材预算：¥{{
                auxiliaryMaterialAmount.totalBudgetAmount
              }}
            </template>
          </div>
          <div class="table-top-btn">
            <el-button type="primary" link @click="openTips">申请材料</el-button>
          </div>
        </div>
        <el-table class="table-wrap" :data="tableData" v-loading="tableLoading" stripe style="width: 100%">
          <el-table-column prop="productName" label="商品/材料名称" width="150" />
          <el-table-column prop="propertiesStr" label="规格" width="150" />
          <el-table-column prop="businessModelCode" label="型号" width="150" />
          <template v-if="radioTabs == 1">
            <el-table-column label="申请量" width="120">
              <template #default="script">
                <div>{{ script.row.buyNum }}{{ script.row.productUnitStr }}</div>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="180">
              <template #default="script">
                <el-tag v-if="script.row.dealState == 3" type="danger" color="#FFE1E1">
                  {{ dealStateOptions.find(item => item.value === String(script.row.dealState))?.label }}
                </el-tag>
                <el-tag v-else-if="['6', '9', '12', '22'].indexOf(script.row.dealState) != -1" type="success">
                  {{ dealStateOptions.find(item => item.value === String(script.row.dealState))?.label }}
                </el-tag>
                <el-tag v-else type="warning">
                  {{ dealStateOptions.find(item => item.value === String(script.row.dealState))?.label }}
                </el-tag>
              </template>
            </el-table-column>
          </template>

          <template v-if="radioTabs == 2">
            <el-table-column label="申请量" width="120">
              <template #default="script">
                <div>{{ script.row.applyNum }}{{ script.row.productUnitStr }}</div>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="180">
              <template #default="script">
                <el-tag v-if="script.row.applyState == 1" type="warning">审核中</el-tag>
                <el-tag v-if="script.row.applyState == 2" type="success">已通过</el-tag>
                <el-tag v-if="script.row.applyState == 3" type="danger" color="#FFE1E1">已拒绝</el-tag>
              </template>
            </el-table-column>
          </template>

          <el-table-column v-if="isJudgmentShowApplyGoodsCost" prop="unitPrice" label="申领成本" width="120" />

          <template v-if="radioTabs == 1">
            <el-table-column prop="receivingAddress" label="收货地址" width="120" />
            <el-table-column prop="orderTime" label="申领时间" width="180" />
          </template>
          <template v-if="radioTabs == 2">
            <el-table-column prop="customerAddress" label="收货地址" width="120" />
            <el-table-column prop="applyTime" label="申领时间" width="180" />
          </template>
          <el-table-column prop="remark" label="备注" width="180" fixed="right" />
        </el-table>
        <custom-pagination :total="listTotal" v-model:page="formData.page" v-model:limit="formData.size" @pagination="getTable" />
      </div>
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref } from "vue";
import { Search } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import {
  contractPage,
  getTaskList,
  judgmentShowApplyGoodsCost,
  getAuxiliaryMaterialAmount,
  getCompleteApplicationPage,
  getApplicationReviewPage
} from "@/apis/engineeringManage/materialApplication";
import { dealStateOptions } from "./config/constant";

const contractList = ref([]);
// 是否加载
const contractLoading = ref(false);
// 是否还有更多数据
const isMore = ref(false);
const contractFrom = ref({
  keyword: "",
  current: 1,
  size: 10
});
// 查询合同
const contractPageApi = async () => {
  contractLoading.value = true;
  await contractPage(contractFrom.value)
    .then(res => {
      contractList.value = [...contractList.value, ...res.data.records];
      // 当前页数*每页条数>=总页数   没有更多数据
      if (contractFrom.value.current == res.data.pages) {
        isMore.value = false;
      } else {
        isMore.value = true;
      }
    })
    .finally(() => {
      contractLoading.value = false;
    });
};

const load = () => {
  if (!isMore.value || contractLoading.value) {
    return;
  }
  contractFrom.value.current++;
  contractPageApi();
};

// 搜索变化
const contractChange = val => {
  contractFrom.value = {
    keyword: val,
    current: 1,
    size: 10
  };
  contractList.value = [];
  contractPageApi();
};

// 左边菜单
const contractId = ref("");
const customerId = ref("");
// 合同变化
const idxChange = val => {
  contractId.value = val.contractId;
  customerId.value = val.customerId;
  getTaskListApi();
  radioTabs.value = 1;
  formData.value = {
    contractId: contractId.value,
    page: 1,
    size: 10
  };
  judgmentShowApplyGoodsCostApi();
};

const stepListLoading = ref(false);
const stepList = ref([]);
// 查询步骤
const getTaskListApi = () => {
  stepListLoading.value = true;
  getTaskList({ customerId: customerId.value })
    .then(res => {
      res.data.forEach(item => {
        item.startDate = item?.startDate?.split(" ")[0];
      });
      stepList.value = res.data;
    })
    .finally(() => {
      stepListLoading.value = false;
    });
};

const bgColor = val => {
  if (val == 1) {
    return {
      backgroundColor: "rgba(10, 201, 5, 0.15)",
      color: "#0AC905"
    };
  }

  if (val == 2) {
    return {
      backgroundColor: "rgba(255, 161, 0, 0.15)",
      color: "#FFA100"
    };
  }

  if (val == 3) {
    return {
      backgroundColor: "rgba(255, 51, 51, 0.15)",
      color: "#FF3333"
    };
  }
};

const openTips = () => {
  ElMessage.warning("当前只支持移动端申领，请在移动端操作");
};

// tabs
const radioTabs = ref(1);
const radioTabsChange = val => {
  formData.value = {
    contractId: contractId.value,
    page: 1,
    size: 10
  };
  tableData.value = [];
  getTable();
};

// 查询当前登录租户是否展示单价
const isJudgmentShowApplyGoodsCost = ref(true);
const judgmentShowApplyGoodsCostApi = () => {
  judgmentShowApplyGoodsCost().then(res => {
    isJudgmentShowApplyGoodsCost.value = res.data;
    if (isJudgmentShowApplyGoodsCost.value) {
      getAuxiliaryMaterialAmountApi();
    }
    getTable();
    getApplicationReviewPageApi();
  });
};

const auxiliaryMaterialAmount = ref({});
// 查询查询辅材已申领/总预算
const getAuxiliaryMaterialAmountApi = () => {
  getAuxiliaryMaterialAmount({ contractId: contractId.value }).then(res => {
    auxiliaryMaterialAmount.value = res.data;
  });
};

const tableLoading = ref(false);
const tableData = ref([]);
const listTotal = ref(0);
const formData = ref({
  page: 1,
  size: 10
});

const applyTotal = ref(0);
// 已申领查询
const getCompleteApplicationPageApi = () => {
  tableLoading.value = true;
  getCompleteApplicationPage(formData.value)
    .then(res => {
      tableData.value = res.data.records;
      listTotal.value = res.data.total;
      applyTotal.value = res.data.total;
    })
    .finally(() => {
      tableLoading.value = false;
    });
};

const applyLoadingTotal = ref(0);
// 申领审核信息查询
const getApplicationReviewPageApi = () => {
  if (radioTabs.value == 2) {
    tableLoading.value = true;
  }
  getApplicationReviewPage(formData.value)
    .then(res => {
      if (radioTabs.value == 2) {
        tableData.value = res.data.records;
        listTotal.value = res.data.total;
      }
      applyLoadingTotal.value = res.data.total;
    })
    .finally(() => {
      if (radioTabs.value == 2) {
        tableLoading.value = false;
      }
    });
};

const getTable = () => {
  if (radioTabs.value == 1) {
    getCompleteApplicationPageApi();
  } else if (radioTabs.value == 2) {
    getApplicationReviewPageApi();
  }
};

onMounted(async () => {
  await contractPageApi();
  if (contractList.value.length > 0) {
    idxChange(contractList.value[0]);
  }
});
</script>
<style scoped lang="scss">
@use "@/assets/styles/mixin";
.material-application {
  height: 100%;
  @include mixin.flex;
  background: #ffffff;
  border-radius: 10px 10px 10px 10px;
}
.page-wrap {
  overflow-y: auto;
  background: #fff;
  border-radius: 10px;
}
// 标题
.box-title {
  display: -webkit-flex;
  align-items: center;

  &-circle {
    display: inline-block;
    width: 6px;
    height: 6px;
    margin-right: 9px;
    border-radius: 50%;
    background-color: #409eff;
  }

  &-label {
    display: inline-block;
    font-size: 18px;
    color: #131414;
    line-height: 24px;
  }
}
.left {
  width: calc(292px - 40px);
  background: #f4f5f7;
  padding: 20px;
  @include mixin.flex-column;
  .left-scrollbar {
    // padding-right: 10px;
    overflow-y: scroll;
    .left-scrollbar-loading {
      text-align: center;
      height: 40px;
      line-height: 40px;
      font-size: 14px;
      // color: #fff;
    }
  }
  .left-input {
    margin: 20px 0;
  }
  .left-item + .left-item {
    margin-top: 10px;
  }
  .left-item {
    height: calc(64px - 16px);
    background: #ffffff;
    box-shadow: 0px 0px 10px 0px rgba(134, 144, 156, 0.1);
    border-radius: 10px 10px 10px 10px;
    padding: 8px 16px;
    border: 2px solid #ffffff;
    cursor: pointer;
    &.active {
      border: 2px solid #007dff;
    }
    .title-name {
      @include mixin.flex;
      margin-top: 3px;
      .name {
        font-size: 14px;
        color: #3d3d3d;
        font-weight: bold;
        width: 70px;
      }
      .title {
        font-size: 14px;
        color: #86909c;
      }
    }
    .contract-type {
      font-size: 12px;
      color: #86909c;
      margin-top: 10px;
    }
  }
}
.right {
  flex: 1;
  overflow-y: scroll;
  .head-scrollbar {
    height: 145px;
    border-bottom: 1px solid #c2d4e8;
    padding: 0 20px;
    .head-list {
      padding: 20px 0;
      @include mixin.flex;
    }
    .head-item {
      flex-shrink: 0;
      width: 120px;
      height: 101px;
      background: #ffffff;
      border: 1px solid #e1e6ed;
      position: relative;
      .item-type {
        padding-left: 10px;
        height: 30px;
        line-height: 30px;
        font-size: 16px;
        &.complete {
          background: #e1e6ed;
          color: #4e5969;
        }
        &.in-progress {
          background: #73a0fa;
          color: #fff;
        }
        &.to-begin {
          background: #fff;
          border-bottom: 1px solid #e1e6ed;
          color: #4e5969;
        }
      }
      .item-text {
        padding-left: 10px;
        margin-top: 15px;
        font-size: 14px;
        color: #3d3d3d;

        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .item-time {
        padding-left: 10px;
        margin-top: 10px;
        font-size: 10px;
        color: #86909c;
      }
      .mask-icon {
        position: absolute;
        right: 0;
        bottom: 0;
        width: 44px;
        height: 53px;
      }

      .item-state {
        position: absolute;
        bottom: 0;
        text-align: center;
        width: 100%;
        height: 16px;
        line-height: 16px;
        border-radius: 5px 5px 0px 0px;
        font-size: 10px;
      }
    }
    .arrow {
      width: 15px;
      height: 15px;
      margin: 10px;
    }
  }
  .right-table {
    padding: 20px;
    .table-top {
      @include mixin.flex-between;
      height: 50px;
      line-height: 50px;
      text-align: center;
      .table-top-tabs {
        @include mixin.flex-center;
        width: 324px;
        background: #f6f8fa;
        .radio {
          ::v-deep(.el-radio-button) {
            &.is-active {
              .el-radio-button__inner {
                border-color: #007dff !important;
              }
            }
            &:last-child {
              .el-radio-button__inner {
                border-left: 1px solid transparent;
              }
            }
            &:last-child.is-active {
              .el-radio-button__inner {
                border-left-width: 1px;
                border-left-style: solid;
              }
            }
          }
        }
      }
      .table-top-text {
        flex: 1;
        margin: 0 5px;
        font-size: 14px;
        color: #1a1a1a;
        background: #f6f8fa;
      }

      .table-top-btn {
        width: 143px;
        background: #f6f8fa;
      }
    }
    // table表头样式
    .table-wrap {
      border: 1px solid #ebeef5;
      border-right: none;
      margin-top: 20px;
      ::v-deep(.el-table__header) {
        th {
          background-color: #f2f6fc !important;
          color: #909399;
        }
      }

      ::v-deep(.el-table__row--striped) {
        td {
          background: #f5f7fa !important;
        }
      }

      ::v-deep(.el-input-number) {
        .el-input__inner {
          text-align: left;
        }
      }
    }
  }
}
</style>
